package Day01.ReflectDemo.DoMain;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectDemo {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, InstantiationException {
        //获取class对象的三种方法
//        1全类名
        Class<?> cls1 = Class.forName("Day01.ReflectDemo.DoMain.Person");

//        2类名.class
        Class cls2 = Person.class;

//        3对象.getclass
        Person person = new Person();
        Class<?> cls3 = person.getClass();

        Class c = Person.class;

//        获取成员变量
        Field name = c.getDeclaredField("name");
        name.setAccessible(true);
        name.set(person, "林青霞");
        System.out.println(person);


//        获取构造方法
        Constructor declaredConstructor = c.getDeclaredConstructor();
        Object obj = declaredConstructor.newInstance();
//        空参  直接class.newInstance
        Object o1 = c.newInstance();

        Constructor constructor = c.getConstructor(String.class, int.class);
        Object o = constructor.newInstance("林青霞", 30);
        System.out.println(o);


//        获取成员方法
        Method getName = c.getMethod("getName");
        Object invoke = getName.invoke(o);
        System.out.println(invoke);

        Method eat = c.getMethod("eat", String.class);
        eat.invoke(o, "饭");


    }
}
